package com.dq.controller;

import com.dq.exception.customException.AdminException;
import com.dq.controller.in.annex.AnnexQuery;
import com.dq.vo.ListVo;
import com.dq.vo.Vo;
import com.dq.vo.baseVo.VO;
import com.dq.domain.activity.Activity;
import com.dq.domain.annex.AnnexTypeEnum;
import com.dq.domain.annex.MallAnnex;
import com.dq.domain.annex.SysAnnex;
import com.dq.domain.category.Category;
import com.dq.domain.goods.Goods;
import com.dq.repository.BaseMallAnnexRepository;
import com.dq.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @创建人 gewenzhen
 * @创建时间 2019/9/10
 * @描述
 */
@Api(description = "附件管理")
@RestController
@RequestMapping("/annex")
public class AnnexController extends AbstractController {
    @Value("${oss-show-url}")
    private String ossShowUrl;

    @Autowired
    BaseMallAnnexRepository baseMallAnnexRepository;

    @ApiOperation("所有附件列表-列表展示")
    @PostMapping("/list")
    public ListVo<MallAnnex.Vo> list(@RequestBody AnnexQuery annexQuery) throws AdminException {
        //查询列表数据
        Map<String, Object> query = annexQuery.parseMap();
        List<MallAnnex> annexes = dao.find(dao.queryAdminHql(MallAnnex.class, query), query);
        Long total = dao.count(dao.countAdminHql(MallAnnex.class, query), query);
        return new ListVo((List<MallAnnex.Vo>) VO.toVOCollection(annexes), total);
    }

    @ApiOperation("商户注册申请上传附件，返回附件id")
    @PostMapping("/deptUpload/{annexTypeEnum}")
    public Vo deptUpload(@ApiParam(value = "商户图片") MultipartFile file, @PathVariable @ApiParam(value = "附件类型") AnnexTypeEnum
            annexTypeEnum) throws IOException {
        String fileName = ossService.upload(FileUtil.save(file));
        MallAnnex mallAnnex = new MallAnnex();
        mallAnnex.setAnnexTypeEnum(annexTypeEnum);
        mallAnnex.setUrlName(fileName);
        mallAnnex.setUrl(ossShowUrl);
        sysAnnexRepository.save(mallAnnex);
        SysAnnex sysAnnex = sysAnnexRepository.findByName(fileName);
        return new Vo(sysAnnex);
    }

    @ApiOperation("用户图片上传")
    @PostMapping("/userUpload/{annexTypeEnum}/{unique}")
    public Vo userUpload(@ApiParam(value = "用户图片") MultipartFile file, @PathVariable @ApiParam(value = "图片类型") AnnexTypeEnum
            annexTypeEnum, @PathVariable @ApiParam(value = "是否一张有效") boolean unique) throws IOException {
        if (unique) {
            SysAnnex sysAnnex = sysAnnexRepository.getBySysUserAndAnnexTypeEnumAndDeletedIsFalse(getUser(),
                    annexTypeEnum);
            if (sysAnnex != null) {
                sysAnnexRepository.delete(sysAnnex);
            }
        }
        String fileName = ossService.upload(FileUtil.save(file));
        MallAnnex mallAnnex = new MallAnnex();
        mallAnnex.setAnnexTypeEnum(annexTypeEnum);
        mallAnnex.setSysUser(getUser());
        mallAnnex.setUrlName(fileName);
        mallAnnex.setUrl(ossShowUrl);
        sysAnnexRepository.save(mallAnnex);
        return new Vo(mallAnnex.getShowUrl());
    }

    @ApiOperation("用户图片获取")
    @GetMapping("/userGet/{annexTypeEnum}")
    public Vo<MallAnnex.Vo> userGet(@PathVariable @ApiParam(value = "图片类型") AnnexTypeEnum annexTypeEnum) {
        List<SysAnnex> sysAnnexs = sysAnnexRepository.findBySysUserAndAnnexTypeEnumAndDeletedIsFalse(getUser(),
                annexTypeEnum);
        return new Vo(VO.toVOCollection(sysAnnexs));
    }

    @ApiOperation("商品图片上传")
    @PostMapping("/goodUpload/{goodId}/{annexTypeEnum}/{unique}")
    public Vo goodUpload(@ApiParam(value = "商品图片") MultipartFile file, @PathVariable @ApiParam(value = "商品id") Long
            goodId, @PathVariable @ApiParam(value = "图片类型") AnnexTypeEnum annexTypeEnum, @PathVariable @ApiParam(value
            = "是否一张有效") boolean unique) throws IOException, AdminException {
        Goods goods = dao.get(Goods.class, goodId);
        if (goods == null) {
            throw new AdminException("未找到商品");
        }
        if (unique) {
            MallAnnex mallAnnex = baseMallAnnexRepository.getByGoodsAndAnnexTypeEnumAndDeletedIsFalse(goods,
                    annexTypeEnum);
            baseMallAnnexRepository.delete(mallAnnex);
        }
        String fileName = ossService.upload(FileUtil.save(file));
        MallAnnex mallAnnex = new MallAnnex();
        mallAnnex.setAnnexTypeEnum(annexTypeEnum);
        mallAnnex.setGoods(goods);
        mallAnnex.setUrlName(fileName);
        mallAnnex.setUrl(ossShowUrl);
        return new Vo(sysAnnexRepository.save(mallAnnex).toVO(false));
    }

    @ApiOperation("删除商品图片")
    @PostMapping("/del/{mallAnnexId}")
    public Vo del(@PathVariable @ApiParam(value = "图片类型") Long mallAnnexId) throws IOException, AdminException {
        MallAnnex annex = dao.get(MallAnnex.class, mallAnnexId);
        if (null == annex) {
            throw new AdminException("未找到附件或图片");
        }
        sysAnnexRepository.delete(annex);
        return new Vo(HttpStatus.OK);
    }

    @ApiOperation("商品图片获取")
    @GetMapping("/goodGet/{goodId}/{annexTypeEnum}")
    public Vo<MallAnnex.Vo> goodGet(@PathVariable @ApiParam(value = "商品id") Long
                                            goodId, @PathVariable @ApiParam(value = "图片类型") AnnexTypeEnum annexTypeEnum) throws AdminException {
        Goods goods = dao.get(Goods.class, goodId);
        if (goods == null) {
            throw new AdminException("未找到商品");
        }
        List<MallAnnex> mallAnnexes = baseMallAnnexRepository.findByGoodsAndAnnexTypeEnumAndDeletedIsFalse(goods,
                annexTypeEnum);
        return new Vo(VO.toVOCollection(mallAnnexes));
    }

    @ApiOperation("分类图片上传")
    @PostMapping("/categoryUpload/{goodId}/{annexTypeEnum}/{unique}")
    public Vo categoryUpload(@ApiParam(value = "分类图片") MultipartFile file, @PathVariable @ApiParam(value = "分类id") Long
            goodId, @PathVariable @ApiParam(value = "图片类型") AnnexTypeEnum annexTypeEnum, @PathVariable @ApiParam(value
            = "是否一张有效") boolean unique) throws IOException, AdminException {
        Category category = dao.get(Category.class, goodId);
        if (category == null) {
            throw new AdminException("未找到该分类");
        }
        if (unique) {
            MallAnnex mallAnnex = baseMallAnnexRepository.getByCategoryAndAnnexTypeEnumAndDeletedIsFalse(category,
                    annexTypeEnum);
            baseMallAnnexRepository.delete(mallAnnex);
        }
        String fileName = ossService.upload(FileUtil.save(file));
        MallAnnex mallAnnex = new MallAnnex();
        mallAnnex.setAnnexTypeEnum(annexTypeEnum);
        mallAnnex.setCategory(category);
        mallAnnex.setUrlName(fileName);
        mallAnnex.setUrl(ossShowUrl);
        sysAnnexRepository.save(mallAnnex);
        return new Vo(mallAnnex.getShowUrl());
    }

    @ApiOperation("分类图片获取")
    @GetMapping("/categoryGet/{goodId}/{annexTypeEnum}")
    public Vo<MallAnnex.Vo> categoryGet(@PathVariable @ApiParam(value = "分类id") Long
                                                goodId, @PathVariable @ApiParam(value = "图片类型") AnnexTypeEnum annexTypeEnum) throws AdminException {
        Category category = dao.get(Category.class, goodId);
        if (category == null) {
            throw new AdminException("未找到该分类");
        }
        List<MallAnnex> mallAnnexes = baseMallAnnexRepository.findByCategoryAndAnnexTypeEnumAndDeletedIsFalse(category,
                annexTypeEnum);
        return new Vo(VO.toVOCollection(mallAnnexes));
    }

    @ApiOperation("删除附件")
    @PostMapping("/delete/{annexId}")
    public Vo delete(@PathVariable @ApiParam(value = "附件id") Long annexId) throws AdminException {
        SysAnnex sysAnnex = dao.get(SysAnnex.class, annexId);
        if (sysAnnex == null) {
            throw new AdminException("未找到该附件");
        }
        sysAnnexRepository.delete(sysAnnex);
        return new Vo(HttpStatus.OK);
    }

    @ApiOperation("图片上传")
    @PostMapping("/upload/{annexTypeEnum}")
    public Vo upload(@ApiParam(value = "图片") MultipartFile file, @PathVariable @ApiParam(value = "图片类型") AnnexTypeEnum annexTypeEnum) throws IOException, AdminException {
        String fileName = ossService.upload(FileUtil.save(file));
        MallAnnex mallAnnex = new MallAnnex();
        mallAnnex.setAnnexTypeEnum(annexTypeEnum);
        mallAnnex.setUrlName(fileName);
        mallAnnex.setName(fileName);
        mallAnnex.setUrl(ossShowUrl);
        baseMallAnnexRepository.save(mallAnnex);
        return new Vo(ossShowUrl + fileName);
    }

    @ApiOperation("单图片上传 返回url 不存入数据库")
    @PostMapping("/upload")
    public Vo uploadOne(@ApiParam(value = "图片") MultipartFile file) throws IOException, AdminException {
        if(!checkFileSize(new File(file.getOriginalFilename()),10,"M")){
            throw new AdminException("文件大小不能超过10M");
        }
        String fileName = ossService.upload(FileUtil.save(file));
        return new Vo(ossShowUrl + fileName);
    }

    @ApiOperation("指令图片上传")
    @PostMapping("/uploadInstructions/{annexTypeEnum}")
    public Vo uploadInstructions(@ApiParam(value = "图片") MultipartFile file, @PathVariable @ApiParam(value = "图片类型") AnnexTypeEnum annexTypeEnum) throws IOException, AdminException {
        String fileName = ossService.upload(FileUtil.save(file));
        MallAnnex mallAnnex = new MallAnnex();
        mallAnnex.setAnnexTypeEnum(annexTypeEnum);
        mallAnnex.setUrlName(fileName);
        mallAnnex.setName(file.getOriginalFilename());
        mallAnnex.setUrl(ossShowUrl);
        baseMallAnnexRepository.save(mallAnnex);
        return new Vo(ossShowUrl + fileName+","+file.getOriginalFilename());
    }

    @ApiOperation("指令附件上传")
    @PostMapping("/uploadFile/{annexTypeEnum}")
    public Vo uploadFile(@ApiParam(value = "商户图片") MultipartFile file, @PathVariable @ApiParam(value = "附件类型") AnnexTypeEnum
            annexTypeEnum) throws IOException {
        int begin = file.getOriginalFilename().indexOf(".");
        int last = file.getOriginalFilename().length();
        String value = file.getOriginalFilename().substring(begin, last);
        if(!".doc".equals(value) && !".zip".equals(value) && !".xls".equals(value)&& !".xlsx".equals(value)&& !".ASM".equals(value) ){
            throw new AdminException("类型有误！您只能上传 DOC、ZIP、xls、xlsx、ASM文件！");
        }
        String fileName = ossService.upload(FileUtil.save(file));
        MallAnnex mallAnnex = new MallAnnex();
        mallAnnex.setAnnexTypeEnum(annexTypeEnum);
        mallAnnex.setUrlName(fileName);
        mallAnnex.setName(file.getName());
        mallAnnex.setUrl(ossShowUrl);
        sysAnnexRepository.save(mallAnnex);
        SysAnnex sysAnnex = sysAnnexRepository.findByName(fileName);
        return new Vo(ossShowUrl + fileName+","+file.getOriginalFilename());
    }

    @ApiOperation("活动图片上传")
    @PostMapping("/activityUpload/{activityId}/{annexTypeEnum}/{unique}")
    public Vo activityUpload(@ApiParam(value = "商品图片") MultipartFile file, @PathVariable @ApiParam(value = "活动id") Long
            activityId, @PathVariable @ApiParam(value = "图片类型") AnnexTypeEnum annexTypeEnum, @PathVariable @ApiParam(value
            = "是否一张有效") boolean unique) throws IOException, AdminException {
        Activity activity = dao.get(Activity.class, activityId);
        if (activity == null) {
            throw new AdminException("未找到活动");
        }
        if (unique) {
            MallAnnex mallAnnex = baseMallAnnexRepository.getByActivityAndAnnexTypeEnumAndDeletedIsFalse(activity,
                    annexTypeEnum);
            baseMallAnnexRepository.delete(mallAnnex);
        }
        String fileName = ossService.upload(FileUtil.save(file));
        MallAnnex mallAnnex = new MallAnnex();
        mallAnnex.setAnnexTypeEnum(annexTypeEnum);
        mallAnnex.setActivity(activity);
        mallAnnex.setUrlName(fileName);
        mallAnnex.setUrl(ossShowUrl);
        return new Vo(sysAnnexRepository.save(mallAnnex).toVO(false));
    }

    /**
     * 判断文件大小
     *
     * @param file
     *            文件
     * @param size
     *            限制大小
     * @param unit
     *            限制单位（B,K,M,G）
     * @return
     */
    public static boolean checkFileSize(File file, int size, String unit) {
        long len = file.length();
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }
}
